/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package spwclient;

import context.Client;
import hibernate.data.*;
import java.util.ArrayList;
import java.util.List;
import javax.swing.table.DefaultTableModel;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

/**
 *
 * @author konp
 */
public class Main extends javax.swing.JFrame {

    private static Client client = new Client();
    private Projects selectedProject = null;
    private ArrayList <Tickets> tickList = null;
    private ArrayList <Users> usersList = null;

    /**
     * Creates new form Main
     */
    public Main(Client client) {
        initComponents();

        this.client = client;
        this.addTic.setEnabled(false);
        this.cancelTask.setEnabled(false);
        this.changeOwner.setEnabled(false);
        this.endTask.setEnabled(false);
        this.ownTask.setEnabled(false);
        this.showTask.setEnabled(false);
        refreshProject();
        //refreshUsers();

    }

    public void refreshProject() {
        Session ses = client.getSession();

        List projects = ses.createCriteria(Projects.class).list();

        for (int i = 0; i < projects.size(); i++) {
            projectBox.addItem(((Projects) projects.get(i)).getPrjName());
        }


    }

    public void refreshUsers() {
        Session ses = client.getSession();
        List groups = ses.createCriteria(Groups.class).add(Restrictions.eq("grpProject", this.selectedProject)).list();
        List users = ses.createCriteria(UserGroups.class).add(Restrictions.in("ugrGroup", groups)).list();
        DefaultTableModel model = (DefaultTableModel) userList.getModel();
        model.setNumRows(users.size());
        for (int i = 0; i < users.size(); i++) {
            Users user = ((UserGroups) users.get(i)).getUgrUser();
            model.setValueAt(user.getUrsLastName(), i, 0);
            model.setValueAt(user.getUrsFirstName(), i, 1);
            model.setValueAt(user.getUrsLogin(), i, 2);
            model.setValueAt(user.getUrsKind().getUksName(), i, 3);
        }
        
        this.usersList = new ArrayList<Users>(users);
        
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        projectBox = new javax.swing.JComboBox();
        openButton = new javax.swing.JButton();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        ticketTable = new javax.swing.JTable();
        jPanel2 = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jPanel4 = new javax.swing.JPanel();
        jButton2 = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        userList = new javax.swing.JTable();
        addTic = new javax.swing.JButton();
        ownTask = new javax.swing.JButton();
        endTask = new javax.swing.JButton();
        changeOwner = new javax.swing.JButton();
        cancelTask = new javax.swing.JButton();
        userBox = new javax.swing.JComboBox();
        showTask = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("Projekt:");

        openButton.setText("Otwórz");
        openButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                openButtonActionPerformed(evt);
            }
        });

        ticketTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null}
            },
            new String [] {
                "Data", "Opis", "Priorytet", "Przydzielony do", "Stan"
            }
        ));
        ticketTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                ticketTableMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(ticketTable);

        jTabbedPane1.addTab("Tickets", jScrollPane1);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 697, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 209, Short.MAX_VALUE)
        );

        jTabbedPane1.addTab("Wiadomości", jPanel2);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 697, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 209, Short.MAX_VALUE)
        );

        jTabbedPane1.addTab("Ustawienia", jPanel1);

        jLabel2.setText("Użytkownicy:");

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 487, Short.MAX_VALUE)
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 449, Short.MAX_VALUE)
        );

        jButton2.setText("Wyloguj");

        userList.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Nazwisko", "Imię", "Login", "Typ"
            }
        ));
        userList.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                userListMouseClicked(evt);
            }
        });
        jScrollPane3.setViewportView(userList);

        addTic.setText("Przydziel zadanie");
        addTic.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addTicActionPerformed(evt);
            }
        });

        ownTask.setText("Utwórz zadanie dla siebie");
        ownTask.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ownTaskActionPerformed(evt);
            }
        });

        endTask.setText("Zakończ zadanie");
        endTask.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                endTaskActionPerformed(evt);
            }
        });

        changeOwner.setText("Zmień odpowiedzialnego na:");
        changeOwner.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                changeOwnerActionPerformed(evt);
            }
        });

        cancelTask.setText("Anuluj zadanie");
        cancelTask.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelTaskActionPerformed(evt);
            }
        });

        showTask.setText("Podgląd zadania");
        showTask.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                showTaskActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 702, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(10, 10, 10)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(showTask)
                                            .addGroup(layout.createSequentialGroup()
                                                .addComponent(ownTask)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addComponent(endTask)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addComponent(cancelTask)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addComponent(changeOwner)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addComponent(userBox, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel2)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addGroup(layout.createSequentialGroup()
                                                .addGap(10, 10, 10)
                                                .addComponent(addTic)))
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(projectBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(openButton))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(235, 235, 235)
                        .addComponent(jButton2)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(projectBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(openButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 237, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(ownTask)
                            .addComponent(endTask)
                            .addComponent(cancelTask)
                            .addComponent(changeOwner)
                            .addComponent(userBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(showTask))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(addTic)
                                .addGap(198, 198, 198)))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton2)
                .addGap(19, 19, 19))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void openButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openButtonActionPerformed
        // TODO add your handling code here:
        String name = (String) this.projectBox.getSelectedItem();
        Session ses = client.getSession();
        List projects = ses.createCriteria(Projects.class).add(Restrictions.eq("prjName", name)).list();
        this.selectedProject = (Projects) projects.get(0);
        this.ownTask.setEnabled(true);
        refreshTickets();

        refreshUsers();


    }//GEN-LAST:event_openButtonActionPerformed

    private void addTicActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addTicActionPerformed
        // TODO add your handling code here:
        String login = (String) userList.getValueAt(userList.getSelectedRow(), 2);

        List users = this.client.getSession().createCriteria(Users.class).add(Restrictions.eq("ursLogin", login)).list();

        Users user = (Users) users.get(0);


        TickWindow tic = new TickWindow(client, selectedProject, user, false, null);
        tic.setVisible(true);
    }//GEN-LAST:event_addTicActionPerformed

    private void userListMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_userListMouseClicked
        // TODO add your handling code here:
        if (client.getUser().getUrsKind().getUksName().equalsIgnoreCase("Admin")
                || client.getUser().getUrsKind().getUksName().equalsIgnoreCase("Project Manager")) {
            this.addTic.setEnabled(true);
        }
    }//GEN-LAST:event_userListMouseClicked

    private void ticketTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ticketTableMouseClicked
        // TODO add your handling code here:
        // TODO add your handling code here:
        int inx = getSelectedTicket();
        this.showTask.setEnabled(true);
        if ((client.getUser().getUrsKind().getUksName().equalsIgnoreCase("Admin")
                || client.getUser().getUrsKind().getUksName().equalsIgnoreCase("Project Manager")) && inx >= 0) {
            this.cancelTask.setEnabled(true);
            this.changeOwner.setEnabled(true);
            this.userBox.setEditable(true);
            
        }else{
            this.cancelTask.setEnabled(false);
            this.changeOwner.setEnabled(false);
            this.userBox.setEditable(false);
        }
        if (this.tickList.get(inx).getUser().getUrsId() == client.getUser().getUrsId()){
            this.endTask.setEnabled(true);
        }else{
            this.endTask.setEnabled(false);
        }
        if(this.tickList.get(inx).getStan() != null && !this.tickList.get(inx).getStan().isEmpty()){
            this.cancelTask.setEnabled(false);
            this.changeOwner.setEnabled(false);
            this.endTask.setEnabled(false);
            this.userBox.setEditable(false);
            this.showTask.setEnabled(false);
        }
        
        if(this.userBox.isEnabled()){
            fillUserBox();
        }
    }//GEN-LAST:event_ticketTableMouseClicked

    private void endTaskActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_endTaskActionPerformed
        // TODO add your handling code here:
        int index = getSelectedTicket();
        
        Tickets tick = this.tickList.get(index);
        tick.setStan("Zakończony");
        this.client.getSession().beginTransaction();
        this.client.getSession().update(tick);
        this.client.getSession().getTransaction().commit();
    }//GEN-LAST:event_endTaskActionPerformed

    private void cancelTaskActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelTaskActionPerformed
        // TODO add your handling code here:
        int index = getSelectedTicket();
        
        Tickets tick = this.tickList.get(index);
        tick.setStan("Anulowany");
        this.client.getSession().beginTransaction();
        this.client.getSession().update(tick);
        this.client.getSession().getTransaction().commit();
    }//GEN-LAST:event_cancelTaskActionPerformed

    private void changeOwnerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_changeOwnerActionPerformed
        // TODO add your handling code here:
        int tickInx = getSelectedTicket();
        int userInx = this.userBox.getSelectedIndex();
        Tickets tick = this.tickList.get(tickInx);
        Users user = this.usersList.get(userInx);
        
        tick.setUser(user);
        
        this.client.getSession().beginTransaction();
        this.client.getSession().update(tick);
        this.client.getSession().getTransaction().commit();
        
    }//GEN-LAST:event_changeOwnerActionPerformed

    private void ownTaskActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ownTaskActionPerformed
        // TODO add your handling code here:
        TickWindow tickW = new TickWindow(client, selectedProject, client.getUser(), false, null);
        tickW.setVisible(true);
    }//GEN-LAST:event_ownTaskActionPerformed

    private void showTaskActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_showTaskActionPerformed
        // TODO add your handling code here:
        int inx = getSelectedTicket();
        Tickets tick = this.tickList.get(inx);
        TickWindow tickW = new TickWindow(client, selectedProject, client.getUser(), true, tick);
        tickW.setVisible(true);
    }//GEN-LAST:event_showTaskActionPerformed

    public void refreshTickets() {
        Session ses = client.getSession();
        List tickets = ses.createCriteria(Tickets.class).add(Restrictions.eq("project", this.selectedProject)).list();

        DefaultTableModel model = (DefaultTableModel) ticketTable.getModel();
        model.setNumRows(tickets.size());
        for (int i = 0; i < tickets.size(); i++) {
            Tickets tic = (Tickets) tickets.get(i);
            model.setValueAt(tic.getDateCreated(), i, 0);
            model.setValueAt(tic.getStatus(), i, 1);
            model.setValueAt(tic.getName(), i, 2);
            model.setValueAt(tic.getUser().getUrsLastName(), i, 3);
            if (tic.getStan() == null || tic.getStan().isEmpty()){
                model.setValueAt("W trakcie", i, 4);
            }
            else{
                model.setValueAt(tic.getStan(), i, 3);
            }
        }
        
        this.tickList = new ArrayList<Tickets>(tickets);

    }
    
    private void fillUserBox(){
        for (int i =0; i<this.usersList.size(); i++){
            userBox.addItem(this.usersList.get(i).getUrsLastName() + " " + this.usersList.get(i).getUrsFirstName());
        }
    }
    
    private int getSelectedTicket(){
        int index;
        
        index = this.ticketTable.getSelectedRow();
        
        return index;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                LoginWindow login = new LoginWindow();
                login.setClient(client);
                login.setVisible(true);

            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addTic;
    private javax.swing.JButton cancelTask;
    private javax.swing.JButton changeOwner;
    private javax.swing.JButton endTask;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JButton openButton;
    private javax.swing.JButton ownTask;
    private javax.swing.JComboBox projectBox;
    private javax.swing.JButton showTask;
    private javax.swing.JTable ticketTable;
    private javax.swing.JComboBox userBox;
    private javax.swing.JTable userList;
    // End of variables declaration//GEN-END:variables
}
